import { createReducer, on, props, Store, createFeatureSelector, createSelector,select } from '@ngrx/store';
import { createAction } from '@ngrx/store';
import { StoreState } from '../index';
import { Injectable } from '@angular/core';

//type ------------------------------------
export interface TestState {
  count: number;
}

//action------------------------------------
export const increment5 = createAction('[Test Component] Increment5', props<{ count: number }>());
export const increment = createAction('[Test Component] Increment');
export const decrement = createAction('[Test Component] Decrement');
export const reset = createAction('[Test Component] Reset');

//State-------------------------------------
export const initialState: TestState = {
  count: 0
};

//Reducer-------------------------------------
const _counterReducer = createReducer(initialState,
  on(increment5, (state, action) => ({ count: state.count + action.count })),
  on(increment, state => ({ count: state.count + 1 })),
  on(decrement, state => ({ count: state.count - 1 })),
  on(reset, state => ({ count: 0 })),
);

export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

//selector--------------------------------------
export const selectTestState = (state: StoreState) => state.test;
// or export const selectFeature = createFeatureSelector<StoreState>('count');
export const selectTestStateCount = createSelector(
  selectTestState,
  (state: TestState) => state.count
);

//封装提供给组件使用
@Injectable({
  providedIn: 'root',
})
export class TestSelectors {
  constructor(private store: Store<StoreState>) {
    //this.store.pipe(select(selectTestStateCount)).subscribe((state) => console.log(state));
  }
  count = this.store.select(selectTestStateCount);

}


